package com.ai.sml.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.sml.util.CacheUtil;
import com.ai.sml.util.StringUtil;

public class ValidateCodeFilter implements Filter {

	private static final Logger logger = LoggerFactory.getUtilLog(ValidateCodeFilter.class);
	
	public void destroy() {
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		
		String cacheImgKey = request.getParameter("cacheImgKey");
		String validateCode = CacheUtil.getFromCache(cacheImgKey);
		String errorT = request.getParameter("errorT");
		String code = request.getParameter("imgCode");
		logger.info("----->>>>>>>>>>cacheImgKey：", cacheImgKey);
		logger.info("----->>>>>>>>>>redis中的校验码：", validateCode);
		logger.info("----->>>>>>>>>>前端传递过来的校验码：", code);
		
		CacheUtil.delFromCache(cacheImgKey);
		
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		if(null == errorT || Integer.parseInt(errorT) >= 3){
			if (StringUtil.isEmpty(code)) {
				out.print("{\"returnCode\":\"3\",\"returnMessage\":\"请输入图片验证码\"}");
				return ;
			}
			if (StringUtil.isNotEmpty(code) && !code.equals(validateCode)) {
				out.print("{\"returnCode\":\"4\",\"returnMessage\":\"错误图片验证码\"}");
				return ;
			}
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
//		requireUrl = new LinkedList<String>();
//		requireUrl.add("/front/sh/login!sendRegisterSmsCode");
//		requireUrl.add("/index/index.html");
	}
	
	/**
	 * 是否需要验证
	 * @param url
	 * @return
	 */
//	public boolean isPass(String url) {
//		return requireUrl.contains(url);
//	}

}
